package com.xpjhs.shiro;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.xpjhs.user.dao.UserDao;
import com.xpjhs.user.model.User;

public class ShiroFilter implements Filter{

	private UserDao userDao;
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpreRequest=(HttpServletRequest) request;
		HttpServletResponse httpResponse=(HttpServletResponse) response;
		Principal principal=httpreRequest.getUserPrincipal();
		if(principal!=null){
			Subject subject=SecurityUtils.getSubject();
			// 为了简单，这里初始化一个用户。实际项目项目中应该去数据库里通过名字取用户：  
            // 例如：User user = userService.getByAccount(principal.getName());
			User user=userDao.findUserByUsername(principal.getName());
			if(user.getUsername().equals(principal.getName())){
				UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), user.getPassword());
				subject=SecurityUtils.getSubject();
				subject.login(token);
				subject.getSession();
			}else {
				if(subject!=null){
					subject.logout();
				}
			}
		}
		chain.doFilter(httpreRequest, httpResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
